package com.link.base.base.user.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.link.base.base.accnt.model.Account;
import com.link.base.base.accnt.service.AccountService;
import com.link.base.base.duty.service.DutyService;
import com.link.base.base.gateway.service.GatewayService;
import com.link.base.base.mvg.model.Mvg;
import com.link.base.base.mvg.service.MvgService;
import com.link.base.base.position.model.Position;
import com.link.base.base.position.service.PositionService;
import com.link.base.base.user.model.OnlineUser;
import com.link.base.base.user.model.User;
import com.link.base.base.user.service.UserService;
import com.link.base.basic.model.ListOfValue;
import com.link.base.user.model.CoreUser;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.interceptor.SecurityInterceptor;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.model.ReturnCodeConstants;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.basic.service.ServiceException;
import com.link.core.cllog.LCLogger;
import com.link.core.util.RedisUtil;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import com.link.core.util.redisclient.LinkRedisClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author unknown
 * @date unknown
 * @comments 用户
 */
@Controller
@RequestMapping("/link/user")
public class UserController extends BasicController<User> {

    private static final Logger logger = LogManager.getLogger(UserController.class);

    @Resource
    private UserService userService;
    @Resource
    private KeyGenerateService keyGenerateService;
    @Resource
    private PositionService positionService;
    @Resource
    private AccountService accountService;
    @Resource
    private DutyService dutyService;
    @Resource
    private MvgService mvgService;

    @Resource
    private GatewayService gatewayService;

    @Override
    public BasicService<User> getBasicService() {
        return userService;
    }


    /**
     * 查询一条记录
     */
    @Override
    @RequestMapping(value = "/queryById")
    @ResponseBody
    public Map<String, Object> queryById(User entity, HttpSession session,
                                         HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        CoreUser user = UserUtil.getUser();
        try {
            if (entity.getId() == null || "".equals(entity.getId())) {
                entity.setId(user.getId());
            }
            User record = getBasicService().queryById(entity);
            List<User> list = new ArrayList<User>();
            list.add(record);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            result.put("result", record);
            result.put("success", true);
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>根据id查询多条用户记录</p>
     *
     * @param ids
     * @param session
     * @param request
     * @param response
     * @return
     * @author yrf
     */
    @RequestMapping(value = "/queryByIds", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryByIds(@RequestParam(value = "ids[]") Long[] ids, HttpSession session,
                                          HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            //如果参数接收不到就尝试从request中取值
            if (null == ids) {
                String strIds = request.getParameter("ids[]");
                if (!StringUtils.isBlank(strIds)) {
                    String[] strIdArray = strIds.split(",");
                    ids = new Long[strIdArray.length];
                    for (int i = 0; i < strIdArray.length; i++) {
                        ids[i] = Long.parseLong(strIdArray[i]);
                    }
                }
            }
            List<User> list = new ArrayList<User>();
            Map<Long, User> map = new HashMap<Long, User>();
            for (Long id : ids) {
                if (id == null) {
                    id = 0L;
                }
                //把查询过的记录放到map里，减少重复查询
                User user = map.get(id);
                if (user == null) {
                    user = new User();
                    user.setId(id);
                    user = userService.querySampleUserById(user);
                    map.put(id, user == null ? new User() : user);
                }
                list.add(map.get(id));
            }
            result.put("success", true);
            result.put("result", list);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }


    /**
     * <p>分页查询外部用户</p>
     *
     * @param qps
     * @param user
     * @param session
     * @param request
     * @param response
     * @return
     * @author yrf
     */
    @RequestMapping(value = "/list/OUTER_EMP", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> listOuter(@JsonParam QueryParams qps, @JsonParam User user,
                                         HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        String userType = "OUTER_EMP";
        user.setEmpTypeLovType(userType);
        qps.addFilter(new Filter("empTypeLovType", userType));
        return this.queryByExamplePage(qps, user, session, request, response);
    }


    /**
     * <p>导出品牌商用户</p>
     *
     * @param user
     * @param qps
     * @param session
     * @param request
     * @param response
     * @return
     * @author HLJ
     */
    @RequestMapping(value = "/queryUsersByType/VendorEmployee/exportData")
    @ResponseBody
    public Map<String, Object> listVenExport(@JsonParam User user, @JsonParam QueryParams qps, HttpSession session,
                                             HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryUsersByType/VendorEmployee/exportData")
                .withMessage("导出品牌商用户列表...").flush();

        String userType = "VendorEmployee";
        qps.addFilter(new Filter("empTypeLovType", userType));
        user.setEmpTypeLovType(userType);
        return this.exportData(user, qps, session, request, response);
    }


    /**
     * <p>导出经销商用户</p>
     *
     * @param user
     * @param qps
     * @param session
     * @param request
     * @param response
     * @return Map
     * @author HLJ
     */
    @RequestMapping(value = "/queryUsersByType/DealerEmployee/exportData")
    @ResponseBody
    public Map<String, Object> listDealerExport(@JsonParam User user, @JsonParam QueryParams qps, HttpSession session,
                                                HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryUsersByType/DealerEmployee/exportData")
                .withMessage("导出经销商用户列表...").flush();

        String userType = "DealerEmployee";
        qps.addFilter(new Filter("empTypeLovType", userType));
        user.setEmpTypeLovType(userType);
        return this.exportData(user, qps, session, request, response);
    }

    /**
     * <p>导出经销商用户</p>
     *
     * @param user
     * @param qps
     * @param session
     * @param request
     * @param response
     * @return Map
     * @author HLJ
     */
    @RequestMapping(value = "/queryUsersByType/TerminalEmployee/exportData")
    @ResponseBody
    public Map<String, Object> listTerminalExport(@JsonParam User user, @JsonParam QueryParams qps, HttpSession session,
                                                  HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryUsersByType/TerminalEmployee/exportData")
                .withMessage("导出门店用户列表...").flush();

        String userType = "TerminalEmployee";
        qps.addFilter(new Filter("empTypeLovType", userType));
        user.setEmpTypeLovType(userType);
        return this.exportData(user, qps, session, request, response);
    }


    /**
     * <p>外部用户新建默认值</p>
     *
     * @return Map
     * @author yrf
     */
    @RequestMapping(value = "/list/OUTER_EMP/preDefaultValue")
    @ResponseBody
    public Map<String, Object> preDefaultValue() {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            User outerUser = userService.outerPreDefaultValue();
            result.put("success", true);
            result.put("result", outerUser);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @Override
    public void beforInsert(User record, HttpServletRequest request) throws Exception {
        User checkUser = userService.getUserByUsername(record.getUsername());
        if (checkUser != null) {
            throw new ServiceException("USER-041", record.getUsername());
        }
        if ("".equals(record.getStatus())) {
            record.setStatus("正常");
        }
        /*if(record.getCorpid().equals("")){

            User user1 = UserUtil.getUser();

            record.setCorpid(user1.getCorpid());
        }*/
    }

    @Override
    public void beforUpsert(User record, HttpServletRequest request) throws Exception {
        if (userService.isInsertFlag(record)) {
            beforInsert(record, request);
        } else {
            beforUpdate(record, request);
        }
    }

    @Override
    public void beforUpdate(User record, HttpServletRequest request) throws Exception {
        User checkUser = userService.getUserByUsername(record.getUsername());
        if (checkUser != null) {
            Long selectId = record.getId();
            Long recordId = checkUser.getId();
            if (!selectId.equals(recordId)) {
                throw new ServiceException("USER-041", record.getUsername());
            }
        }
    }

    /**
     * <p>生成密码，默认联系电话后六位</p>
     *
     * @param record
     * @param session
     * @param request
     * @param response
     * @return Map
     * @author yrf
     */
    @RequestMapping(value = "/genPsw", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updatePostn(@JsonParam User record, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            userService.genPsw(record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 更新DMS
     */
    @RequestMapping(value = "/updateDmsProfile")
    @ResponseBody
    public Map<String, Object> updateProfile(@JsonParam User entity, HttpSession session,
                                             HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            beforUpdate(entity, request);
            beforUpsert(entity, request);
            checkData(entity, request);
            String base = "base";
            if (!checkExistDataCache("base", session, entity)) {
                throw new ServiceException("PUBLIC-002");
            }
            userService.updateDmsProfile(entity);

            User newEntry = userService.queryById(entity);
            session.setAttribute("UserContext", newEntry);
            result.put("newRow", newEntry);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 获取年月
     */
    @RequestMapping(value = "/list/{type}")
    @ResponseBody
    public Object list(@PathVariable String type, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        List<ListOfValue> list = new ArrayList<ListOfValue>();
        try {
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMM");
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.MONTH, -2);
            int three = 3;
            for (int i = 0; i < three; i++) {
                cal.add(Calendar.MONTH, 1);
                Date date = cal.getTime();
                String date1 = sdf1.format(date);
                String date2 = sdf2.format(date);
                ListOfValue record = new ListOfValue();
                record.setType(type);
                record.setName(date1);
                record.setVal(date2);
                list.add(record);
            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        return list;
    }

    @RequestMapping(value = "/listOfVal/{type}")
    @ResponseBody
    public Map<String, Object> listOfValTypes(@PathVariable String type, HttpSession session,
                                              HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        List<ListOfValue> list = new ArrayList<ListOfValue>();
        try {
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMM");
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.MONTH, -2);
            int three = 3;
            for (int i = 0; i < three; i++) {
                cal.add(Calendar.MONTH, 1);
                Date date = cal.getTime();
                String date1 = sdf1.format(date);
                String date2 = sdf2.format(date);
                ListOfValue record = new ListOfValue();
                record.setType(type);
                record.setName(date1);
                record.setVal(date2);
                list.add(record);
            }
            result.put("success", true);
            result.put("rows", list);
            result.put("total", list.size());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<ListOfValue>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 重写basic中的方法
     * 新建或更新一条记录
     */
    @RequestMapping(value = "/upsertUser")
    @ResponseBody
    public Map<String, Object> upsert(@JsonParam User user, @JsonParam QueryParams qps, HttpSession session,
                                      HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            beforUpsert(user, request);
            checkData(user, request);
            String base = "base";
            if (!getBasicService().isInsertFlag(user) && !checkExistDataCache(base, session, user)) {
                throw new ServiceException("PUBLIC-002");
            }
            getBasicService().upsert(user);

            if (user.getCorpid() != null) {
                System.out.println("复制用户mvg...");
                userService.copyUserMvgInfo(user, qps);
            }

            User newUser = getBasicService().queryById(user);
            result.put("newRow", newUser);
            result.put("success", true);
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 新建门店账号
     *
     * @throws Exception
     */
    @RequestMapping(value = "/upsertUserNew")
    @ResponseBody
    public Map<String, Object> upsertUser(@JsonParam User user, @JsonParam QueryParams qps, HttpSession session, HttpServletRequest request,
                                          HttpServletResponse response) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            //User user2 = UserUtil.getUser();
            result = beforUpsertUser(user, request);
            Position position = new Position();
            Account account = new Account();
            account.setId(user.getAcctId());
            account = accountService.queryById(account);
            String newStr = "NEW";
            String storeManager = "StoreManager";
            String shoppingGuide = "ShoppingGuide";
            String update = "UPDATE";
            if (newStr.equals(user.getRow_status())) {
                if (storeManager.equals(user.getPositionType())) {
                    // 角色为店长
                    position.setOrgId(account.getOrgId());
                    position.setDeptId(account.getOrgId());
                    position.setPageFlag(false);
                    List<Position> positions = positionService.queryByExamplePage(position);
                    for (int i = 0; i < positions.size(); i++) {
                        if (("StoreManager").equals(positions.get(i).getPositionType())) {
                            throw new ServiceException("USER-042");
                        }
                    }
                    position.setText(account.getAcctName() + "-" + user.getFirstName());
                    position.setPositionType("StoreManager");
                    positionService.insert(position);
                    user.setPostnId(position.getId());
                } else if (shoppingGuide.equals(user.getPositionType())) {
                    // 角色为导购

                    position.setText(account.getAcctName() + "-" + user.getFirstName());
                    position.setPositionType("ShoppingGuide");
                    position.setOrgId(account.getOrgId());
                    position.setDeptId(account.getOrgId());
                    positionService.insert(position);
                    user.setPostnId(position.getId());
                }
            } else if (update.equals(user.getRow_status())) {
                Position updatePosition = positionService.queryById(user.getPostnId());
                if (storeManager.equals(user.getPositionType())) {
                    // 角色为店长
                    position.setOrgId(account.getOrgId());
                    position.setPageFlag(false);
                    List<Position> positions = positionService.queryByExamplePage(position);
                    for (int i = 0; i < positions.size(); i++) {
                        if (("StoreManager").equals(positions.get(i).getPositionType())
                                && !user.getId().equals(positions.get(i).getUserId())) {
                            throw new ServiceException("USER-042");
                        }
                    }
                    updatePosition.setPositionType("StoreManager");
                    positionService.update(updatePosition);
                } else if (shoppingGuide.equals(user.getPositionType())) {
                    // 角色为导购
                    updatePosition.setPositionType("ShoppingGuide");
                    positionService.update(updatePosition);
                }
            }
            String base = "base";
            if (!getBasicService().isInsertFlag(user) && !checkExistDataCache(base, session, user)) {
                throw new ServiceException("PUBLIC-002");
            }
            getBasicService().upsert(user);

            if (user.getCorpid() != null) {
                System.out.println("复制用户mvg...");
                userService.copyUserMvgInfo(user, qps);
            }

            User newUser = getBasicService().queryById(user);
            //新增User_postn中间表
            if (newStr.equals(user.getRow_status())) {
                Mvg mvg = new Mvg();
                //userid
                mvg.setMvgParentId(user.getId());
                //postnid
                mvg.setMvgSubsetId(position.getId());
                //  mvg.setMvgMapperName("userPostn");
                mvgService.setMvgMapperName("userPostn");
                mvgService.insert(mvg);

                User userDuty = new User();
                userDuty.setDutyId(user.getDutyId());
                userDuty.setId(user.getId());
                dutyService.addUserOfDutyInsert(userDuty);
            }
            result.put("newRow", newUser);
            result.put("success", true);
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /***
     * 根据不同类型判断查询用户
     * 分页查询传入类型用户
     * @param user
     * @param eType 类型
     * @param qps
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/queryUsersByType/{eType}", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryUsersByType(@JsonParam User user, @PathVariable(value = "eType", required = true) String eType,
                                                @JsonParam QueryParams qps,
                                                HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        if (org.apache.commons.lang3.StringUtils.isEmpty(eType)) {
            throw new ServiceException("USER-043");
        }
        qps.preDealSecurity(request);
        qps.addFilter(new Filter("empTypeLovType", eType));
        //user.setEmpTypeLovType(eType);
        // qps.addSorter(new Sorter("id", Sorter.DIR_ASC));
        return this.queryByExamplePage(qps, user, session, request, response);
    }

    @RequestMapping(value = "/queryUsersBySource/{source}")
    @ResponseBody
    public Map<String, Object> queryUsersBySource(@PathVariable(value = "source", required = true) String source,
                                                  @JsonParam QueryParams qps,
                                                  HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(4);
        try {
            qps.preDealSecurity(request);
            if (StringUtils.isBlank(source)) {
                throw new ServiceException("USER-043");
            }
            User temp = BasicModel.transformClass(User.class, qps);
            temp.setSource(source);
            beforQueryAllOrExample(temp, request);
            beforQueryExample(temp, request);
            List<User> list = userService.queryUsersBySource(temp);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(temp, list.size()));
            result.put("code", ReturnCodeConstants.SUCCESS);
        } catch (BasicServiceException e) {
            result.put("success", false);
            result.put("rows", new ArrayList<T>());
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getDetailMessage());
            result.put("code", e.getCode());
        } catch (Exception e) {
            logger.error("BasicController捕获异常: ", e);
            result.put("success", false);
            result.put("rows", new ArrayList<T>());
            result.put("result", e.getMessage());
            result.put("code", ReturnCodeConstants.EXCEPTION);
        }
        return result;
    }



    private void beforUpdateUser(User user, HttpServletRequest request) {


    }

    private void beforInsertUser(User user, HttpServletRequest request) {
        User checkUser = userService.getUserByUsername(user.getUsername());
        if (checkUser != null) {
            throw new ServiceException("USER-041", user.getUsername());
        }

    }

    private Map<String, Object> beforUpsertUser(User user, HttpServletRequest request) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        if (userService.isInsertFlag(user)) {
            beforInsertUser(user, request);
        } else {
            beforUpdateUser(user, request);
        }
        return result;
    }


    /***
     * 根据不同类型获取预创建数据
     * 暂时仅对，门店，经销商用户可用
     * @param eType
     * @return
     */
    @RequestMapping(value = "/preDefaultValueByType/{eType}")
    @ResponseBody
    public Map<String, Object> preDefaultValueByType(@PathVariable String eType) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            User outerUser = userService.outerPreDefaultValue();
            result.put("success", true);
            result.put("result", outerUser);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /***
     * 从redis中获取在线用户
     * 假分页，假搜索
     * @param user
     * @param qps
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/queryUserListFromRedis", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryUserListFromRedis(@JsonParam User user, @JsonParam QueryParams qps,
                                                      HttpSession session, HttpServletRequest request,
                                                      HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>();
        LinkRedisClient jedis = null;
        try {
            CoreUser currentUser = UserUtil.getUser();
            Long corpId = currentUser.getCorpid() == null ? -1L : currentUser.getCorpid();
            Long standardCorpId = 0L;
            qps.preDealSecurity(request);
            List<OnlineUser> userOrigList = new ArrayList<>();
            //从redis里拿到所有以auth_user_为开头的键值对
            jedis = RedisUtil.getJedis();

            //拿到所有符合条件的key
            List<String> keyList = jedis.scan(1000, "auth_user_*");
            if (keyList.size() <= 0) {
                result.put("success", true);
                result.put("result", null);
                result.put("total", 0);
                return result;
            }
            JSONArray array = JSONObject.parseArray(qps.getFiltersRaw());
            List<String> tokenList = new ArrayList<>();

            String usernameField = "";
            String firstNameField = "";
            String loginType = null;
            for (int i = 0; i < array.size(); i++) {
//                username\firstName\loginType
                String property = ((JSONObject) array.get(i)).getString("property");

                if ("loginType".equals(property)) {
                    loginType = ((JSONObject) array.get(i)).getString("value");
                    if (StringUtils.isNotBlank(loginType)) {
                        loginType = loginType.trim();
                    }
                } else if ("username".equals(property)) {
                    usernameField = ((JSONObject) array.get(i)).getString("value");
                    if (StringUtils.isNotBlank(usernameField)) {
                        usernameField = usernameField.trim();
                    }

                } else if ("firstName".equals(property)) {
                    firstNameField = ((JSONObject) array.get(i)).getString("value");
                    if (StringUtils.isNotBlank(firstNameField)) {
                        firstNameField = firstNameField.trim();
                    }
                }
                if (StringUtils.isNotBlank(loginType)) {
                    String[] tokenSp = null;
                    String scope = "";
                    for (String token : keyList) {
                        tokenSp = token.split("_");
                        scope = tokenSp[2];
                        if (loginType.equals(scope)) {
                            tokenList.add(token);
                        }
                    }
                }
            }

            String[] keyArr;
            if (StringUtils.isBlank(loginType)) {
                keyArr = new String[keyList.size()];
            } else {
                keyArr = new String[tokenList.size()];
            }

            if (keyArr.length < 1) {
                result.put("success", true);
                result.put("result", userOrigList);
                result.put("total", userOrigList.size());
                return result;
            }

            if (StringUtils.isBlank(loginType)) {
                keyList.toArray(keyArr);
            } else {
                tokenList.toArray(keyArr);
            }

            List<String> values = jedis.mget(keyArr);

            if (StringUtils.isBlank(firstNameField) && StringUtils.isBlank(usernameField)) {
                if (standardCorpId.equals(corpId)) {
                    for (int i = 0; i < keyArr.length; ++i) {

                        OnlineUser userOrig = JSON.parseObject(values.get(i), OnlineUser.class);
                        userOrig.setReKey(keyArr[i]);
                        userOrigList.add(userOrig);
                    }
                } else {
                    for (int i = 0; i < keyArr.length; ++i) {
                        OnlineUser userOrig = JSON.parseObject(values.get(i), OnlineUser.class);
                        userOrig.setReKey(keyArr[i]);
                        if (corpId.equals(userOrig.getCorpid())) {
                            userOrigList.add(userOrig);
                        }
                    }
                }
            } else {
                if (standardCorpId.equals(corpId)) {
                    for (int i = 0; i < keyArr.length; ++i) {
                        OnlineUser userOrig = JSON.parseObject(values.get(i), OnlineUser.class);
                        String username = userOrig.getUsername() == null ? "" : userOrig.getUsername();
                        String firstname = userOrig.getFirstName() == null ? "" : userOrig.getFirstName();
                        if (StringUtils.isNotBlank(firstNameField)) {
                            if ((firstname.indexOf(firstNameField)) != -1) {
                                System.out.println(values.get(i));
                                userOrig.setReKey(keyArr[i]);
                                userOrigList.add(userOrig);
                            }
                            continue;
                        }

                        if (StringUtils.isNotBlank(usernameField)) {
                            if ((username.indexOf(usernameField)) != -1) {
                                System.out.println(values.get(i));
                                userOrig.setReKey(keyArr[i]);
                                userOrigList.add(userOrig);
                            }
                        }
                    }
                } else {
                    for (int i = 0; i < keyArr.length; ++i) {
                        OnlineUser userOrig = JSON.parseObject(values.get(i), OnlineUser.class);
                        String username = userOrig.getUsername() == null ? "" : userOrig.getUsername();
                        String firstname = userOrig.getFirstName() == null ? "" : userOrig.getFirstName();
                        //从请求参数里拿到筛选条件，原始查询的list数据进行筛选，达到假搜索的目的
                        if (corpId.equals(userOrig.getCorpid())) {
                            if (StringUtils.isNotBlank(firstNameField)) {
                                if ((firstname.indexOf(firstNameField)) != -1) {
                                    userOrig.setReKey(keyArr[i]);
                                    userOrigList.add(userOrig);
                                }
                                continue;
                            }
                            if (StringUtils.isNotBlank(usernameField)) {
                                if ((username.indexOf(usernameField)) != -1) {
                                    userOrig.setReKey(keyArr[i]);
                                    userOrigList.add(userOrig);
                                }
                            }

                        }
                    }
                }
            }
            result.put("success", true);
            result.put("result", userOrigList);
            result.put("total", userOrigList.size());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        } finally {
            RedisUtil.returnResource(jedis);
        }
        return result;
    }

    /***
     * 从redis中获取在线用户
     * @param qps
     * @param request
     * @return
     */
    @RequestMapping(value = "/queryUserCateInfo", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryUserCateInfo(@JsonParam QueryParams qps,
                                                 HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        Map<String, List<OnlineUser>> onlineUsers = new HashMap();
        LinkRedisClient jedis = null;
        try {
            CoreUser currentUser = UserUtil.getUser();
            Long corpId = currentUser.getCorpid() == null ? -1L : currentUser.getCorpid();
            Long standardCorpId = 0L;
            qps.preDealSecurity(request);
            //从redis里拿到所有以auth_user_为开头的键值对
            jedis = RedisUtil.getJedis();
            //拿到所有符合条件的key
            List<String> keyList = jedis.scan(1000, "auth_user_*");
            if (keyList.size() <= 0) {
                result.put("success", true);
                result.put("result", onlineUsers);
                result.put("total", 0);
                return result;
            }
            String[] keyArr = new String[keyList.size()];
            keyList.toArray(keyArr);
            List<String> values = jedis.mget(keyArr);
            if (standardCorpId.equals(corpId)) {
                for (int i = 0; i < keyArr.length; ++i) {
                    OnlineUser userOrig = JSON.parseObject(values.get(i), OnlineUser.class);
                    String key = keyArr[i];
                    userOrig.setReKey(key);
                    String[] s = key.split("_");
                    if (s.length > 3) {
                        String tokenScope = s[2];
                        List<OnlineUser> userList = onlineUsers.getOrDefault(tokenScope, new ArrayList<>());
                        userList.add(userOrig);
                        onlineUsers.put(tokenScope, userList);
                    }
                }
            } else {
                for (int i = 0; i < keyArr.length; ++i) {
                    OnlineUser userOrig = JSON.parseObject(values.get(i), OnlineUser.class);
                    userOrig.setReKey(keyArr[i]);
                    if (corpId.equals(userOrig.getCorpid())) {
                        String key = keyArr[i];
                        userOrig.setReKey(key);
                        String tokenScope = StringUtils.substringAfterLast(key, "_");
                        List<OnlineUser> userList = onlineUsers.getOrDefault(tokenScope, new ArrayList<>());
                        userList.add(userOrig);
                        onlineUsers.put(tokenScope, userList);
                    }
                }
            }
            result.put("success", true);
            result.put("result", onlineUsers);
            result.put("total", keyArr.length);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        } finally {
            RedisUtil.returnResource(jedis);
        }
        return result;
    }

    /***
     * 从redis中获取在线用户
     * 假分页，假搜索
     * @param user
     * @param qps
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/queryOnlineUserCount", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryOnlineUserCount(@JsonParam User user, @JsonParam QueryParams qps,
                                                    HttpSession session, HttpServletRequest request,
                                                    HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>();

        CoreUser currentUser = UserUtil.getUser();
        Long corpId = currentUser.getCorpid() == null ? -1L : currentUser.getCorpid();
        Long standardCorpId = 0L;

        LinkRedisClient jedis = null;
        try {
            //从redis里拿到所有以auth_user_为开头的键值对
            jedis = RedisUtil.getJedis();
            List<String> keyList = jedis.scan(1000, "auth_user_*");

            int onlineUserCount = 0;
            if (standardCorpId.equals(corpId)) {
                onlineUserCount = keyList.size();
            } else {
                String[] keyArr = new String[keyList.size()];
                keyList.toArray(keyArr);
                List<String> values = jedis.mget(keyArr);
                for (int i = 0; i < keyList.size(); ++i) {
                    OnlineUser userOrig = JSON.parseObject(values.get(i), OnlineUser.class);
                    userOrig.setReKey(keyArr[i]);
                    if (corpId.equals(userOrig.getCorpid())) {
                        onlineUserCount++;
                    }
                }
            }
            result.put("success", true);
            result.put("result", onlineUserCount);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        } finally {
            RedisUtil.returnResource(jedis);
        }
        return result;
    }

    @RequestMapping(value = "/quitUser")
    @ResponseBody
    public Map<String, Object> quitUser(OnlineUser onlineUser, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        LinkRedisClient jedis = null;
        try {
            String token = request.getHeader(SecurityInterceptor.INNER_TOKEN);
            jedis = RedisUtil.getJedis();
            if (!StringUtils.isBlank(onlineUser.getReKey())) {
                String reKey = onlineUser.getReKey().replace("auth_user_", "");
                jedis.del(reKey);
                jedis.del("auth:" + reKey);
                jedis.del("access:" + reKey);
                jedis.del("login_info_" + reKey);
                jedis.del(onlineUser.getReKey());
            }

            gatewayService.invalidateToken(onlineUser, token);

            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        } finally {
            RedisUtil.returnResource(jedis);
        }
        return result;
    }

    /**
     * 移动端-更新用户信息
     *
     * @author ouyangzhenqiang
     * @date 2018/11/1
     */
    @RequestMapping(value = "/updateUserInfo", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateUserInfo(@RequestBody User record,
                                              HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            CoreUser user = UserUtil.getUser();
            record.setId(user.getId());
            userService.updateUserInfo(record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 会员模块——根据corpid 查询User
     *
     * @author guguishan
     * @date 2018/2/15
     */
    @RequestMapping(value = "/queryUserByCorpId", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryUserByCorpId(@RequestParam("corpid") Long corpid,
                                                 HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            User user = userService.queryUserByCropId(corpid);
            result.put("success", true);
            result.put("result", user);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 会员模块——根据username 查询User
     *
     * @author yangxiaolin
     * @date 2018/3/28
     */
    @RequestMapping(value = "/queryByUserName", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryByUserName(@RequestBody User user,
                                               HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            user = userService.queryByUserName(user.getUsername());
            result.put("success", true);
            result.put("result", user);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 根据传入的ORGID获取他及他下级组织的所有用户
     *
     * @param entity
     * @param qps
     * @return Map
     * @author 黄正杨
     * @date 2019/4/23
     */
    @RequestMapping({"/selectByOrgIdPage"})
    @ResponseBody
    public Map<String, Object> selectByOrgIdPage(@JsonParam QueryParams qps, @JsonParam User entity,
                                                 HttpSession session, HttpServletRequest request,
                                                 HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(8);
        try {
            qps.preDealSecurity(request);
            User temp = BasicModel.transformClass(entity, qps);
            List<User> list = userService.selectByOrgIdPage(temp);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(temp, list.size()));
            result.put("code", "200");
        } catch (ServiceException e) {
            result.put("success", false);
            result.put("rows", new ArrayList());
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
            result.put("code", e.getCode());
        } catch (Exception e) {
            result.put("success", false);
            result.put("rows", new ArrayList());
            result.put("result", e.getMessage());
            result.put("code", "400");
        }
        return result;
    }

    /**
     * 重置sessionKey
     *
     * @author LiQun
     * @date 2019/4/13 15:39
     */
    @RequestMapping(value = "/resetSessionKey", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryUserByCropId(@RequestBody Account record) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            userService.resetSessionKey(record.getIntegrateCode(), record.getIntegrateId(), record.getSession_key());
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 通过用户名获取用户,提供给微信工程调用
     *
     * @author 黄龙建
     * @date 2020年06月11日
     */
    @RequestMapping(value = "/getUserByUsername", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getUserByUsername(@RequestParam("username") String username) {
        Map<String, Object> result = new HashMap<>();
        try {
            User user = userService.getUserByUsername(username);
            result.put("success", true);
            result.put("result", user);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

}



